<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left" />
      <template v-for="(btn, index) in btnArray">
        <template v-if="btn.permission">
          <el-button
            :key="index"
            slot="reference"
            v-permission="btn.permission"
            class="filter-item"
            size="mini"
            :type="buttonType(btn)"
            :icon="getIcon(btn)"
            :disabled="disabled(btn)"
            @click="handleClick(btn)"
          >
            {{ buttonName(btn) }}
          </el-button>
        </template>
        <template v-else>
          <el-button
            :key="index"
            class="filter-item"
            size="mini"
            :type="buttonType(btn)"
            :icon="getIcon(btn)"
            :disabled="disabled(btn)"
            @click="handleClick(btn)"
          >{{ buttonName(btn) }}</el-button>
        </template>
      </template>
      <slot name="right" />
    </span>
    <el-button-group class="crud-opts-right">
      <el-button
        size="mini"
        plain
        type="info"
        icon="el-icon-search"
        @click="toggleSearch()"
      />
      <el-button
        size="mini"
        icon="el-icon-refresh"
        @click="crud.refresh()"
      />
      <el-popover
        placement="bottom-end"
        width="150"
        trigger="click"
      >
        <el-button
          slot="reference"
          size="mini"
          icon="el-icon-s-grid"
        >
          <i
            class="fa fa-caret-down"
            aria-hidden="true"
          />
        </el-button>
        <el-checkbox
          v-model="allColumnsSelected"
          :indeterminate="allColumnsSelectedIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox
          v-for="item in crud.props.tableColumns"
          :key="item.label"
          v-model="item.visible"
          @change="handleCheckedTableColumnsChange(item)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-popover>
    </el-button-group>
  </div>
</template>
<script>
import CRUD, { crud } from '@crud/crud'
export default {
  mixins: [crud()],
  props: {
    /**
     *{
     * name         按钮名称
     * type         按钮类型(必填项,add、edit、delete、download)
     * position     按钮位置(0-全部,1-top,2-right,默认0)
     * buttonType   按钮样式
     * permission   按钮权限(['admin','user:add'])
     * handleClick  点击事件处理
     * params       点击事件参数
     * selections   edit、delete选项
     *}
     */
    permissions: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      buttonTypes: {
        'add': 'primary',
        'edit': 'success',
        'delete': 'danger',
        'download': 'warning'
      },
      buttonNames: {
        'add': '新增',
        'edit': '修改',
        'delete': '删除',
        'download': '导出'
      }
    }
  },
  computed: {
    btnArray() {
      return this.permissions.filter(item => {
        return !item.position || item.position === 1
      })
    }
  },
  created() {
    this.crud.updateProp('searchToggle', true)
  },
  methods: {
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    },
    buttonType(btn) {
      const buttonType = btn.buttonType
      const type = btn.type
      if (!buttonType) {
        return this.buttonTypes[type]
      }
      return buttonType
    },
    getIcon(btn) {
      let res = 'el-icon-plus'
      if (btn.type === 'edit') {
        res = 'el-icon-edit'
      } else if (btn.type === 'delete') {
        res = 'el-icon-delete'
      } else if (btn.type === 'download') {
        res = 'el-icon-download'
      }
      return res
    },
    disabled(btn) {
      const { type, selections = 1 } = btn
      const crud = this.crud
      let res = false
      if (type === 'delete') {
        res = crud.selections.length === 0
      } else if (type === 'edit') {
        switch (selections) {
          case 1:
            res = crud.selections.length !== 1
            break
          case 2:
            res = crud.selections.length === 0
            break
        }
      }
      return res
    },
    buttonName(btn) {
      const name = btn.name
      const type = btn.type
      if (!name) {
        return this.buttonNames[type]
      }
      return name
    },
    handleClick(btn) {
      const handleClick = btn.handleClick
      let handleFun = null
      let target = this
      let params = []
      const crud = this.crud

      if (handleClick) {
        handleFun = this.$parent[handleClick]
        params = btn.params || []
        target = this.$parent
      } else {
        switch (btn.type) {
          case 'add':
            handleFun = crud.toAdd
            target = crud
            break
          case 'edit':
            handleFun = crud.toEdit
            target = crud
            params.push(crud.selections[0])
            break
          case 'delete':
            handleFun = this.toDelete
            target = this
            params.push(crud.selections)
            break
          case 'download':
            handleFun = crud.doExport
            target = crud
            break
        }
      }

      handleFun.apply(target, params)
    }
  }
}
</script>

<style>
  .crud-opts {
    padding: 6px 0;
    display: -webkit-flex;
    display: flex;
    align-items: center;
  }
  .crud-opts .crud-opts-right {
    margin-left: auto;
  }
</style>
